package com.example.jpa.controller;

import com.example.jpa.domain.User;
import com.example.jpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: ThinkPad
 * Date: 2021-04-24 17:38
 * This is my work in reachauto code.
 * mail:chenxiangning@reachauto.com
 * Description:
 */
@RequestMapping(path = "/users")
@RestController
public class UserController {

    @Autowired
    private UserRepository userRepository;


    @RequestMapping(value = "", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
    public Map findAll() {
        List<User> users = userRepository.findAll();

        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "访问成功");
        map.put("data", users);
        return map;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
    public Map findById(@PathVariable("id") Long id) {

        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "访问成功");
        map.put("data", userRepository.findById(id).get());
        return map;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = {MediaType.APPLICATION_JSON_VALUE})
    public Map dropId(@PathVariable("id") Long id) {
        userRepository.deleteById(id);
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "访问成功");
        return map;
    }

    @RequestMapping(value = "", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE})
    public Map save(@RequestBody User user) {
        user = userRepository.save(user);
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "访问成功");
        map.put("data", user);
        return map;
    }


}
